package com.shanghai.shanghaielectric.UI;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.shanghai.shanghaielectric.Constants;
import com.shanghai.shanghaielectric.DataAdapter.Cells2ShowAdapter;
import com.shanghai.shanghaielectric.Model.ReceiveDataModel;
import com.shanghai.shanghaielectric.Model.WriteDataModel;
import com.shanghai.shanghaielectric.R;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_Alert;
import com.shanghai.shanghaielectric.communicate.OnSerialReceiveListener;
import com.shanghai.shanghaielectric.communicate.SerialAPI;
import com.shanghai.shanghaielectric.communicate.VoltagePhaseSequence;
import com.shanghai.shanghaielectric.entity.CapacitorEntity;
import com.shanghai.shanghaielectric.utils.CapacitanceStateView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import shanghaielectric_lib.MyEventBus.EventBus_showCells;
import shanghaielectric_lib.Utils.LogUtil;
import shanghaielectric_lib.Utils.dwin.BitUtils;


public class Active_reActiveFragment extends Fragment {

    public View monitorBasicView;
    private TextView mVoltagePhaseSequenceTv;//刷新主页电压相序：正序 负序
    private CapacitanceStateView mStateView;//电容状态显示   刷新界面的图形

    List<Button> buttonList;
    //    @BindView(R.id.bt_capacitor_cutting_clear)
//    Button btCapacitorCuttingClear;
    @BindView(R.id.tv_capacitor_cutting_state)
    TextView tvCapacitorCuttingState;
    @BindView(R.id.v_active_reactive_light_GB1)
    View vActiveReactiveLightGB1;
    @BindView(R.id.v_active_reactive_light_GB2)
    View vActiveReactiveLightGB2;
    @BindView(R.id.v_active_reactive_light_GB3)
    View vActiveReactiveLightGB3;
    @BindView(R.id.v_active_reactive_light_GB4)
    View vActiveReactiveLightGB4;
    @BindView(R.id.v_active_reactive_light_FB1A)
    View vActiveReactiveLightFB1A;
    @BindView(R.id.v_active_reactive_light_FB1B)
    View vActiveReactiveLightFB1B;
    @BindView(R.id.v_active_reactive_light_FB1C)
    View vActiveReactiveLightFB1C;
    @BindView(R.id.v_active_reactive_light_FB2A)
    View vActiveReactiveLightFB2A;
    @BindView(R.id.v_active_reactive_light_FB2B)
    View vActiveReactiveLightFB2B;
    @BindView(R.id.v_active_reactive_light_FB2C)
    View vActiveReactiveLightFB2C;
    @BindView(R.id.v_active_reactive_light_FB3A)
    View vActiveReactiveLightFB3A;
    @BindView(R.id.v_active_reactive_light_FB3B)
    View vActiveReactiveLightFB3B;
    @BindView(R.id.v_active_reactive_light_FB3C)
    View vActiveReactiveLightFB3C;
    @BindView(R.id.tv_reactive_stateCode)
    TextView tvReactiveStateCode;
    Unbinder unbinder;
    @BindView(R.id.tv_gb1)
    TextView tvGb1;
    @BindView(R.id.tv_gb2)
    TextView tvGb2;
    @BindView(R.id.tv_gb3)
    TextView tvGb3;
    @BindView(R.id.tv_gb4)
    TextView tvGb4;
    @BindView(R.id.tv_fb1a)
    TextView tvFb1a;
    @BindView(R.id.tv_fb1b)
    TextView tvFb1b;
    @BindView(R.id.tv_fb1c)
    TextView tvFb1c;
    @BindView(R.id.tv_fb2a)
    TextView tvFb2a;
    @BindView(R.id.tv_fb2b)
    TextView tvFb2b;
    @BindView(R.id.tv_fb2c)
    TextView tvFb2c;
    @BindView(R.id.tv_fb3a)
    TextView tvFb3a;
    @BindView(R.id.tv_fb3b)
    TextView tvFb3b;
    @BindView(R.id.tv_fb3c)
    TextView tvFb3c;
    private boolean isDebug = false;
    private View fragment_active_reactiveView;
    LayoutInflater myInflater;
    Context mContext;
    WriteDataModel writeDataModel = Constants.writeDataModel;
    Cells2ShowAdapter cells2ShowAdapter;
    List<View> lights;
    List<TextView> textViewList;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        System.out.println("Debugging____onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("Debugging____onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println("Debugging____onCreateView");
        fragment_active_reactiveView = inflater.inflate(R.layout.fragment_active_reactive,
                container, false);
        myInflater = (LayoutInflater) getActivity().getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        mContext = getActivity().getApplicationContext();
        getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//        //隐藏软键盘
//        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        unbinder = ButterKnife.bind(this, fragment_active_reactiveView);

        initView();

        initViews();

        initData();
        initListener();
        //点击其他部位隐藏软键盘
        fragment_active_reactiveView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (getActivity().getCurrentFocus() != null && getActivity().getCurrentFocus().getWindowToken() != null) {
                        manager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                return false;
            }
        });

        return fragment_active_reactiveView;
    }

    private void initListener() {
        EventBus.getDefault().register(this);

    }

    private void initData() {

        cells2ShowAdapter = new Cells2ShowAdapter();
//        for (int i = 0; i <buttonList.size() ; i++) {
//            int resourceID=writeDataModel.getTestCapacitor1(i)?R.drawable.btn_pressed:R.drawable.btn_default;
//            buttonList.get(i).setTextColor(resourceID);
//        }
    }

    public void initView() {
        lights = new ArrayList<>();
        lights.add(vActiveReactiveLightGB1);
        lights.add(vActiveReactiveLightGB2);
        lights.add(vActiveReactiveLightGB3);
        lights.add(vActiveReactiveLightGB4);
        lights.add(vActiveReactiveLightFB1A);
        lights.add(vActiveReactiveLightFB1B);
        lights.add(vActiveReactiveLightFB1C);
        lights.add(vActiveReactiveLightFB2A);
        lights.add(vActiveReactiveLightFB2B);
        lights.add(vActiveReactiveLightFB2C);
        lights.add(vActiveReactiveLightFB3A);
        lights.add(vActiveReactiveLightFB3B);
        lights.add(vActiveReactiveLightFB3C);
        textViewList = new ArrayList<>();
        textViewList.add(tvGb1);
        textViewList.add(tvGb2);
        textViewList.add(tvGb3);
        textViewList.add(tvGb4);
        textViewList.add(tvFb1a);
        textViewList.add(tvFb1b);
        textViewList.add(tvFb1c);
        textViewList.add(tvFb2a);
        textViewList.add(tvFb2b);
        textViewList.add(tvFb2c);
        textViewList.add(tvFb3a);
        textViewList.add(tvFb3b);
        textViewList.add(tvFb3c);

    }


////////////////////////////////////控件移植////////////////////////////////////
    private void initViews() {
//        mStateView = (CapacitanceStateView) view.findViewById(R.id.monitor_state_view);//电容状态显示   刷新界面的图形
        mStateView = fragment_active_reactiveView.findViewById(R.id.monitor_state_view);

//        mVoltagePhaseSequenceTv = (TextView) view.findViewById(R.id.monitor_voltage_phase_sequence);//电压相序：正序，负序
        mVoltagePhaseSequenceTv = fragment_active_reactiveView.findViewById(R.id.monitor_voltage_phase_sequence);//电压相序：正序，负序

        SerialAPI.getInstance().registerListener(mSerialListener);
//        CapacitorEntity entity = SerialAPI.getInstance().getCapacitorEntity();//此处没有拿到实体，显示空异常entity=null;
        CapacitorEntity entity = new CapacitorEntity();//重新获取 新对象  是显示出来了！！！
        mStateView.refreshData(entity.getListRes());//获取 电容的图形资源  刷新界面
        mStateView.refreshTvData(entity.mPassiveType);//刷新  电容上的数值
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("Debugging____onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("Debugging____onStart");
    }

    @Override
    public void onResume() {
        super.onResume();

//        //隐藏软键盘
//        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        System.out.println("Debugging____onResume");
    }

    @Override
    public void onPause() {
        super.onPause();

        System.out.println("Debugging____onPause");
    }

    @Override
    public void onStop() {
        super.onStop();

        System.out.println("Debugging____onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("Debugging____onDestroyView");
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        System.out.println("Debugging____onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("Debugging____onDetach");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveCellsData_(EventBus_showCells eventBusShowCells) {

        ReceiveDataModel receiveDataModel = new Cells2ShowAdapter().cells2ReceiveDataModel(eventBusShowCells.cell_showMap);
        (textViewList.get(receiveDataModel.capacityIndex)).setText(receiveDataModel.capacityCuttingTimes);
//        lights.get(receiveDataModel.capacityIndex).setBackgroundResource(R.drawable.point_green);
        for (int i = 0; i < 12; i++) {
            int resourceID = BitUtils.getBit(receiveDataModel.DIO_1, i + 4) ? R.drawable.point_green : R.drawable.point_gray;
            lights.get(i).setBackgroundResource(resourceID);
        }
        lights.get(12).setBackgroundResource(BitUtils.getBit(receiveDataModel.DIO_1, 0) ? R.drawable.point_green : R.drawable.point_gray);

        tvReactiveStateCode.setText(receiveDataModel.reactiveStateCode);

        LogUtil.e("reactive", "接收到变化");

    }

    private void showDiolg(String commandName) {
        Dialog_Alert diolgAlert = new Dialog_Alert();
        diolgAlert.setCommandName(commandName);
        diolgAlert.show(this.getFragmentManager(), "");
    }

/*    @OnClick(R.id.bt_capacitor_cutting_clear)
    public void onViewClicked() {
        showDiolg("是否下发投切清零命令？");
        Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
            @Override
            public void onClink(boolean flag) {
                if (flag) {
                    Toast.makeText(mContext, "正在发送“投切清零命令”", Toast.LENGTH_SHORT).show();
                    Constants.writeDataModel.cleareSwitchTimes = 1;
                    CommunicateManager.sendData();
                }
            }
        });
    }*/

    //新增串口接收监听器
    private OnSerialReceiveListener mSerialListener = new OnSerialReceiveListener() {
        @Override
        public void onVoltagePhaseSequence(VoltagePhaseSequence sequence) {
            mVoltagePhaseSequenceTv.setText(sequence.msg);//电压相序  需要  ：正序
        };

        @Override
        public void onCapacitorState(CapacitorEntity entity) {
            mStateView.refreshData(entity.getListRes());//传入  获取的电容开关状态
            mStateView.refreshTvData(entity.mPassiveType);// 传入对应的 电容的数值
        }

    };


}
